<template>
	<div class="payment-page">
		<!-- 商品清单 -->
		<div class="product-section">
			<div class="section-title">活动清单</div>
			<div class="product-list">
				<div class="product-item">
					<img :src="orderData.activity_spec_info.activity_cover_path" class="product-image" />
					<div class="product-info">
						<div class="product-name">{{ orderData.activity_spec_info.activity_title }}</div>
						<div class="product-time">
							{{ orderData.activity_spec_info.activity_start_at }}-{{ orderData.activity_spec_info.activity_end_at }}
						</div>
					</div>
				</div>
			</div>
			<div class="product-footer">
				<div class="product-price">￥{{ orderData.activity_spec_info.activity_price }}元/位</div>
			</div>
		</div>

		<!-- 个人信息 -->
		<div class="user-info-section">
			<div class="section-title">个人信息</div>
			<div class="input-group">
				<div class="input-label">姓名</div>
				<input 
					type="text" 
					placeholder="请输入姓名（至少2个字）" 
					v-model="user_full_name" 
					class="custom-input" 
					@blur="validateName"
				/>
				<div v-if="nameError" class="error-message">{{ nameError }}</div>
			</div>
			<div class="input-group">
				<div class="input-label">手机号</div>
				<input 
					type="tel" 
					placeholder="请输入手机号" 
					v-model="user_phone" 
					class="custom-input"
					maxlength="11"
					@blur="validatePhone"
				/>
				<div v-if="phoneError" class="error-message">{{ phoneError }}</div>
			</div>
		</div>

		<!-- 支付方式 -->
		<div class="payment-method">
			<div class="section-title">支付方式</div>
			<div class="method-item" @click="selectPayment('wechat')">
				<img src="https://shalong.taiyanyue.top/images/st-weixinzhifu1.png" class="payment-icon" />
				<div class="method-name">微信支付</div>
				<img v-if="paymentMethod === 'wechat'" src="https://shalong.taiyanyue.top/images/fa5-check-circle-fas1.png" class="selected-icon" />
				<img v-else src="https://shalong.taiyanyue.top/images/weixuanz.png" class="unselected-icon" />
			</div>
		</div>

		<!-- 底部支付栏 -->
		<div class="footer-bar">
			<div class="total-amount">
				<span>待支付</span>
				<span class="amount">¥{{ orderData.activity_spec_info.activity_price }}</span>
			</div>
			<button 
				class="pay-button" 
				@click="pay"
				:disabled="!isFormValid"
				:class="{ 'disabled-button': !isFormValid }"
			>
				{{ isFormValid ? '支付' : '请填写完整信息' }}
			</button>
		</div>
	</div>
</template>

<script>
	import {
		order_activitySignUp,
		payment
	} from '@/api/system/user.js'
	export default {
		data() {
			return {
				paymentMethod: 'wechat',
				orderData: {},
				user_full_name: "",
				user_phone: "",
				phoneError: "",
				nameError: ""
			}
		},
		computed: {
			isFormValid() {
				return (
					this.user_full_name.trim() !== "" &&
					this.user_phone.trim() !== "" &&
					!this.phoneError &&
					!this.nameError
				);
			}
		},
		onLoad(options) {
			if (options.data) {
				const receivedData = JSON.parse(decodeURIComponent(options.data));
				console.log('接收到的数据:', receivedData);
				this.orderData = receivedData;
				
				// 合并姓氏和名字
				if (receivedData.user_info) {
					const lastName = receivedData.user_info.user_last_name || "";
					const firstName = receivedData.user_info.user_first_name || "";
					this.user_full_name = lastName + firstName;
				}
				this.user_phone = receivedData.user_info?.user_phone || "";
			}
		},
		methods: {
			selectPayment(method) {
				this.paymentMethod = method;
			},
			validatePhone() {
				const phoneRegex = /^1[3-9]\d{9}$/;
				if (!this.user_phone) {
					this.phoneError = "请输入手机号";
				} else if (!phoneRegex.test(this.user_phone)) {
					this.phoneError = "请输入正确的手机号";
				} else {
					this.phoneError = "";
				}
			},
			validateName() {
				if (!this.user_full_name.trim()) {
					this.nameError = "请输入姓名";
				} else if (this.user_full_name.length < 2) {
					this.nameError = "姓名至少需要2个字";
				} else {
					this.nameError = "";
				}
			},
			async pay() {
			    if (!this.isFormValid) return;
			    
			    // 验证姓名
			    this.validateName();
			    if (this.nameError) return;
			    
			    // 验证手机号
			    this.validatePhone();
			    if (this.phoneError) return;
			    
			    uni.showLoading({
			        title: '支付中...',
			        mask: true
			    });
			    
			    try {
			        // 1. 调用后端接口创建订单并获取支付参数
			        const payParams = {
			            activity_id: this.orderData.activity_spec_info.activity_id,
			            activity_spec_id: this.orderData.activity_spec_info.activity_spec_id,
			            sign_up_name: this.user_full_name.trim(),
			            sign_up_phone: this.user_phone
			        };
			        
			        // 调用后端接口创建订单并获取支付参数
			        const res = await order_activitySignUp(payParams);
			        
			        if (res.code === 200) {
			            // 2. 调用微信支付
			            const ddbh = res.content.data.activity_order_sn; 
			            payment({
			            	order_sn: ddbh,
			            	order_type:1
			            }).then(res => {
			            	// 调用微信支付API
			            	console.log(res,'1111')
			            	const paymentData = res.content.data.data;
			            	this.requestPayment(paymentData);
			            }).catch(res=>{
			            	uni.hideLoading();
			            	console.error('支付失败:');
			            	uni.showToast({
			            	    title: '支付失败，请重试',
			            	    icon: 'none',
			            	    duration: 2000
			            	});
			            })
			        } else {
			            uni.hideLoading();
			            uni.showToast({
			                title: res.msg || '订单创建失败',
			                icon: 'none',
			                duration: 2000
			            });
			        }
			    } catch (error) {
			        uni.hideLoading();
			        console.error('支付失败:', error);
			        uni.showToast({
			            title: '支付失败，请重试',
			            icon: 'none',
			            duration: 2000
			        });
			    }
			},
			requestPayment(paymentData) {
			    return new Promise((resolve, reject) => {
			        uni.requestPayment({
			            provider: 'wxpay', // 微信支付
						appid:paymentData.appId,
			            timeStamp: paymentData.timeStamp, // 支付签名时间戳
			            nonceStr: paymentData.nonceStr, // 支付签名随机串
			            package: paymentData.package, // 统一下单接口返回的 prepay_id 格式如：prepay_id=***
			            signType: paymentData.signType || 'MD5', // 签名算法
			            paySign: paymentData.paySign, // 支付签名
			            success: (res) => {
			               uni.hideLoading();
			               uni.showToast({
			               	title: '支付成功',
			               	icon: 'success',
			               	duration: 1500
			               });
			               				
			               // 跳转到支付成功页面或订单详情页
			               uni.navigateBack({
			               	delta: 1
			               });
			               resolve(true);
			            },
			            fail: (err) => {
			                console.error('支付失败:', err);
			                if (err.errMsg.includes('cancel')) {
			                    uni.showToast({
			                        title: '已取消支付',
			                        icon: 'none',
			                        duration: 2000
			                    });
			                }
			                reject(err);
			            }
			        });
			    });
			}
		}
	}
</script>

<style scoped>
	.payment-page {
		background-color: #f8f8f8;
		min-height: 100vh;
		padding-bottom: 90px;
		padding-top: 10px;
	}
	
	/* 公共样式 */
	.section-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-bottom: 15px;
	}
	
	/* 商品清单样式 */
	.product-section {
		background: #fff;
		margin: 0 12px 10px;
		padding: 15px;
		border-radius: 12px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
	}
	
	.product-item {
		display: flex;
		padding: 10px 0;
	}
	
	.product-image {
		width: 80px;
		height: 80px;
		margin-right: 12px;
		border-radius: 8px;
		object-fit: cover;
	}
	
	.product-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}
	
	.product-name {
		font-size: 15px;
		color: #333;
		line-height: 1.4;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}
	
	.product-time {
		font-size: 12px;
		color: #999;
		margin-top: 5px;
	}
	
	.product-footer {
		display: flex;
		justify-content: flex-end;
		margin-top: 15px;
		padding-top: 10px;
		border-top: 1px solid #f5f5f5;
	}
	
	.product-price {
		font-size: 16px;
		color: #369a68;
		font-weight: bold;
	}
	
	/* 用户信息样式 */
	.user-info-section {
		background: #fff;
		margin: 0 12px 10px;
		padding: 15px;
		border-radius: 12px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
	}
	
	.input-group {
		margin-bottom: 15px;
	}
	
	.input-label {
		font-size: 14px;
		color: #666;
		margin-bottom: 8px;
	}
	
	.custom-input {
		width: 100%;
		height: 44px;
		border: 1px solid #eee;
		border-radius: 8px;
		padding: 0 12px;
		font-size: 14px;
		background-color: #f9f9f9;
		transition: all 0.3s;
	}
	
	.custom-input:focus {
		border-color: #369a68;
		background-color: #fff;
	}
	
	.error-message {
		font-size: 12px;
		color: #ff4d4f;
		margin-top: 5px;
	}
	
	/* 支付方式样式 */
	.payment-method {
		background: #fff;
		padding: 15px;
		margin: 0 12px 10px;
		border-radius: 12px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
	}
	
	.method-item {
		display: flex;
		align-items: center;
		padding: 12px 0;
	}
	
	.payment-icon {
		width: 24px;
		height: 24px;
		margin-right: 12px;
	}
	
	.method-name {
		flex: 1;
		font-size: 15px;
		color: #333;
	}
	
	.selected-icon,
	.unselected-icon {
		width: 20px;
		height: 20px;
	}
	
	/* 底部支付栏样式 */
	.footer-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: #fff;
		padding: 10px 15px;
		border-top: 1px solid #f0f0f0;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
	}
	
	.total-amount {
		flex: 1;
	}
	
	.total-amount span {
		font-size: 14px;
		color: #666;
	}
	
	.amount {
		font-size: 20px;
		color: #369a68;
		font-weight: bold;
		margin-left: 5px;
	}
	
	.pay-button {
		background: #369a68;
		color: #fff;
		border: none;
		border-radius: 22px;
		height: 44px;
		width: 150px;
		font-size: 16px;
		font-weight: bold;
		transition: all 0.3s;
	}
	
	.disabled-button {
		background: #ccc;
		color: #999;
	}
</style>